<template>
  <div class="lazy-image-container" :class="{ 'loading': !isLoaded, 'loaded': isLoaded }">
    <!-- 占位符 -->
    <div v-if="!isLoaded" class="placeholder">
      <div class="loading-spinner"></div>
      <span class="loading-text">Loading...</span>
    </div>

    <!-- 实际图片 -->
    <img
      :src="isLoaded ? src : ''"
      :alt="alt"
      :class="['lazy-image', { 'fade-in': isLoaded }]"
      @load="onImageLoad"
      @error="onImageError"
      v-show="isLoaded"
    />
  </div>
</template>

<script>
export default {
  name: 'LazyImage',
  props: {
    src: {
      type: String,
      required: true
    },
    alt: {
      type: String,
      default: ''
    },
    threshold: {
      type: Number,
      default: 0.1
    },
    rootMargin: {
      type: String,
      default: '50px 0px'
    }
  },
  data() {
    return {
      isLoaded: false,
      observer: null
    }
  },
  mounted() {
    this.setupIntersectionObserver();
  },
  beforeUnmount() {
    if (this.observer) {
      this.observer.disconnect();
    }
  },
  methods: {
    setupIntersectionObserver() {
      this.observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            this.isLoaded = true;
            this.observer.unobserve(entry.target);
          }
        });
      }, {
        threshold: this.threshold,
        rootMargin: this.rootMargin
      });

      this.observer.observe(this.$el);
    },
    onImageLoad() {
      this.$emit('load');
    },
    onImageError() {
      this.$emit('error');
    }
  }
}
</script>

<style scoped>
.lazy-image-container {
  position: relative;
  overflow: hidden;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 200px;
  color: #999;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

.loading-text {
  font-size: 14px;
  color: #666;
}

.lazy-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
}

.lazy-image.fade-in {
  opacity: 1;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loaded .placeholder {
  display: none;
}
</style>
